﻿using lhx_VoteSys.Models;
using lhx_VoteSys.Models.Database;
using lhx_VoteSys.service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace lhx_VoteSys.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class UserController : Controller
    {
        private readonly lhx_VoteSysContext _db;
        private readonly IJWTService _jwtService;
        public UserController(lhx_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            if (request.Password != request.CirPassword)
                return "两次密码输入不一致";

            if (_db.Users.Any(x => x.Email == request.Email))
                return "邮箱已存在";

            _db.Users.Add(new User
            {
                Email = request.Email,
                Password = request.Password,
            });
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);
            if (user == null)
                return "用户不存在";
            if (user.Password != request.Password)
                return "密码不正确";
            return _jwtService.CreateToken(user.Id, user.Email);
        }
    }
}
